package com.example.mode.activity;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.mode.R;

public class SportActivity extends AppCompatActivity {

    private TextView tvSportFrequency;
    private TextView tvHeartRate;
    private TextView tvHeartRateWarning;
    private Button btnStartStop;

    private boolean isSporting = false;
    private int sportFrequency = 0;
    private int heartRate = 0;
    private final int HIGH_HEART_RATE_THRESHOLD = 120; // 心率过高阈值

    private Handler handler = new Handler();
    private Runnable updateRunnable = new Runnable() {
        @Override
        public void run() {
            if (isSporting) {
                // 模拟运动频率和心率变化
                sportFrequency = (int) (Math.random() * 30) + 30;
                heartRate = (int) (Math.random() * 80) + 60;

                tvSportFrequency.setText(sportFrequency + " 次/分钟");
                tvHeartRate.setText(heartRate + " 次/分钟");

                if (heartRate > HIGH_HEART_RATE_THRESHOLD) {
                    tvHeartRateWarning.setVisibility(View.VISIBLE);
                    tvHeartRateWarning.setText("心率过高，请适当休息！");
                } else {
                    tvHeartRateWarning.setVisibility(View.GONE);
                }

                handler.postDelayed(this, 1000); // 每秒更新一次
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sport);

        tvSportFrequency = findViewById(R.id.tv_sport_frequency);
        tvHeartRate = findViewById(R.id.tv_heart_rate);
        tvHeartRateWarning = findViewById(R.id.tv_heart_rate_warning);
        btnStartStop = findViewById(R.id.btn_start_stop);

        btnStartStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isSporting) {
                    stopSport();
                } else {
                    startSport();
                }
            }
        });
    }

    private void startSport() {
        isSporting = true;
        btnStartStop.setText("停止运动");
        handler.post(updateRunnable);
    }

    private void stopSport() {
        isSporting = false;
        btnStartStop.setText("开始运动");
        handler.removeCallbacks(updateRunnable);
        tvSportFrequency.setText("0 次/分钟");
        tvHeartRate.setText("0 次/分钟");
        tvHeartRateWarning.setVisibility(View.GONE);
    }
}